<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Staff
 *
 * @author tuanbao
 */
class Staff extends Users
{

    public $verifyCode;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Staff the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('email, author_id', 'required'),
            array('email', 'email'),
            array('email', 'validateTime'),
            array('author_id', 'numerical'),
            array('password, new_pass', 'length', 'min' => 6),
            array('firstname, lastname, password, repassword', 'length', 'max' => 32),
            array('status, postal_code, gender, business_id', 'length', 'max' => 20),
            array('occupation, type, address, address2, business_name, business_type, website, contract_start, 
                contract_end, facebook, twitter, gplus, instagram',
                'length', 'max' => 255
            ),
            array('city, tax_id, fax', 'length', 'max' => 255),
            //Change password
            array('old_pass, new_pass, renewpass', 'required', 'on' => 'changepassword'),
            array('old_pass', 'checkOldPassword', 'on' => 'changepassword'),
            array('renewpass', 'compare', 'compareAttribute' => 'new_pass', 'on' => 'changepassword'),
            //Forgot password
            array('renewpass', 'compare', 'compareAttribute' => 'new_pass', 'on' => 'forgotpass'),
            //Change Email
            array('newmail, renewmail', 'required', 'on' => 'changeemail'),
            array('renewmail', 'compare', 'compareAttribute' => 'newmail', 'on' => 'changeemail'),
            array('newmail, renewmail', 'email', 'on' => 'changeemail'),
            //Create customer in Appointment

            /**
             * Create User
             */
            //Staff
            array(
                'email, new_pass, repassword, mobile_phone, nickname',
                'required',
                'on' => 'create_' . self::TYPE_STAFF
            ),
            array('repassword', 'compare', 'compareAttribute' => 'new_pass', 'on' => 'create_' . self::TYPE_STAFF),
            array('repassword', 'compare', 'compareAttribute' => 'new_pass', 'on' => 'edit_' . self::TYPE_STAFF),
            array(
                'email, mobile_phone, nickname',
                'required',
                'on' => 'edit_' . self::TYPE_STAFF
            ),
            array(
                'mobile_phone',
                'numerical',
//                'on' => 'edit_' . self::TYPE_STAFF
            ),
            array(
                'office_phone,mobile_phone',
                'check_validate_phone',
//                'on' => 'edit_' . self::TYPE_STAFF
            ),
            array('nickname', 'safe'),
//            array(
//                'new_pass',
//                'unsafe',
//                'on' => 'edit_' . self::TYPE_STAFF
//            ),
            /**
             * Quy định về các trường dữ liệu của User không được tự ý sửa
             */
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('profile, repassword, note, facebook, twitter, gplus, instagram, office_phone, home_phone, mobile_phone, country, photo, business_description, business_slogan', 'safe'),
            array('id, nickname,firstname, lastname, gender, occupation, address, address2, city, country, postal_code, type, status, business_id, business_name, business_type, business_logo, business_description, business_slogan, tax_id, website, email, author_id, date_created, facebook, twitter, gplus, instagram, latitude , longitude', 'safe', 'on' => 'search'),
            array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'on' => 'signup'),
        );
    }

    public function check_validate_phone($attribute, $params)
    {
        if ($this->$attribute != '')
        {
            $a = trim($this->$attribute);
            $a = str_replace(' ', '', $a);
            if (!in_array($a[0], array('6', '9', '8')))
            {
                $this->addError($attribute, Yii::t('main', 'Please provide a valid phone number'));
            }
            return;
        }
    }

    public function validateTime($attribute, $params)
    {
        //compare start_time vs end_time
        if (!$this->checkUniqueEmail())
        {
            $this->addError($attribute, Yii::t('main', 'Email was registered'));
            return;
        }
    }

    private function checkUniqueEmail()
    {
        if (!isset($this->email))
            return FALSE;

        $criteria            = new CDbCriteria();
        $criteria->select    = array('email,type');
        $criteria->condition = 'email=:email AND type=:t';
        $criteria->params    = array(
            ':email' => $this->email,
            ':t'     => Users::TYPE_STAFF
        );

        if (!$this->isNewRecord)
        {
            $criteria->addCondition('id!=' . $this->id);
        }

        $staff = Users::model()->find($criteria);

        //neu co staff
        if ($staff)
            return FALSE;

        return TRUE;
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);

        $criteria->compare('email', $this->email, true);
        $criteria->compare('nickname', $this->nickname, true);
        $criteria->compare('type', $this->type, true);
        $criteria->compare('status', $this->status, true);

        // $criteria->compare('firstname', $this->firstname, true);
        //$criteria->compare('lastname', $this->lastname, true);

        $criteria->compare('author_id', $this->author_id, true);

        if (($firstname = Yii::app()->request->getQuery('firstname', '')) != '')
        {
            //echo $firstname;die;
            $criteria->compare('firstname', $firstname, true);
        }
        if (($lastname = Yii::app()->request->getQuery('lastname', '')) != '')
        {
            $criteria->compare('lastname', $lastname, true);
        }
        if (($email = Yii::app()->request->getQuery('email', '')) != '')
        {
            $criteria->compare('email', $email, TRUE);
        }

        if (($nickname = Yii::app()->request->getQuery('nickname', '')) != '')
        {
            $criteria->compare('nickname', $nickname, TRUE);
        }
        $filterBusiness = null;
        //Is merchant
        $criteria->compare('type', Users::TYPE_STAFF);
        if (user()->isMerchant())
        {
//            $criteria->condition = 'type=:t';
//            $criteria->params = CMap::mergeArray($criteria->params,array(
//                ':t' => Users::TYPE_STAFF
//            ));
            //Root merchant
            $list_branch_ids = Merchant::get_id_all_branch(user()->id, TRUE);
            $criteria->addInCondition('author_id', $list_branch_ids);
        }
        elseif (user()->isAdmin())
        {
            if (isset($_GET['pk']))
            {
                $filterBusiness = $_GET['pk'];
            }
            else
            {
                $bizArray = Users::getAllBussiness(TRUE);
                foreach ($bizArray as $bizId => $bizName)
                {
                    $filterBusiness = $bizId;
                    break;
                }
            }

            $criteria->compare('author_id', Users::getIdByUkey($filterBusiness));
        }
        elseif (user()->isBranch())
        {
            $criteria->compare('author_id', user()->id);
        }

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

}
